/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rlpw.util;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author weinpau
 */
public class ForgetfulList<T> extends AbstractList<T> {

    private List<Entry> entries = new ArrayList<Entry>();
    private double defaultForgettingRate = .2;

    public ForgetfulList() {
    }

    public ForgetfulList(double defaultRate) {
        setDefaultForgettingRate(defaultRate);
    }

    private void forget() {
        for (int i = 0; i < entries.size(); i++) {
            if (entries.get(i).isLose()) {
                entries.remove(entries.get(i));
            }
        }
    }

    public double getDefaultForgettingRate() {
        return defaultForgettingRate;
    }

    public void setDefaultForgettingRate(double defaultForgettingRate) {
        this.defaultForgettingRate = defaultForgettingRate;
    }

    public int size() {
        return entries.size();
    }

    @Override
    public boolean add(T entry) {
        return add(entry, getDefaultForgettingRate());
    }

    public boolean add(T entry, double forgetrate) {
        boolean result = entries.add(new Entry(forgetrate, entry));
        if (result) {
            forget();
        }

        return result;

    }

    public T get(int index) {
        return (T) entries.get(index).getEntry();
    }

    @Override
    public String toString() {

        String result = "";
        for (T e : this) {
            result += e.toString() + "\n";
        }

        return result;
    }

    private class Entry  {

        private double rate, sum = 0;
        private T entry;

        public Entry(double rate, T entry) {
            this.rate = rate;
            this.entry = entry;
        }

        public T getEntry() {
            return entry;
        }

        public double getRate() {
            return rate;
        }

        public double getSum() {
            return sum;
        }

        public boolean isLose() {
            sum += rate;
            return (sum > 1);
        }

     
        @Override
        public String toString() {
            return entry.toString() + " (life remaining: " + (int) ((1 - getSum()) / getRate()) + ")";
        }
    }
}
